package handler

import (
	"fmt"
	"strconv"
	"strings"

	"gitee.com/chenhonghua/ginorigin/http/restful"
	"gitee.com/chenhonghua/ginorigin/log"
	"github.com/gin-gonic/gin"

	"gitee.com/chenhonghua/common-service/cmd/segment/client"
)

func init() {
	restful.RegisterErrorFromCodeAndMessage(10001, "查询错误：关键词不能为空")
	restful.RegisterErrorFromCodeAndMessage(10002, "查询错误：错误的页码，页码必须大于0")
	restful.RegisterErrorFromCodeAndMessage(10003, "查询错误：错误的分页尺寸，分页尺寸必须大于0且小于100")
}

type queryParam struct {
	Kws     []string
	Subject string
	Page    int
	Size    int
}

func NewQueryParam(ctx *gin.Context) (*queryParam, *restful.E) {
	kw := strings.TrimSpace(ctx.Query("kw"))
	if len(kw) == 0 {
		return nil, restful.Errors.FromCode(10001)
	}
	subject := strings.TrimSpace(ctx.Query("subject"))
	page, e := strconv.Atoi(strings.TrimSpace(ctx.Query("page")))
	if e != nil {
		log.Warn(e)
		return nil, restful.Errors.FromCode(10002)
	} else if page <= 0 {
		return nil, restful.Errors.FromCode(10002)
	}
	size, e := strconv.Atoi(strings.TrimSpace(ctx.Query("size")))
	if e != nil {
		log.Warn(e)
		return nil, restful.Errors.FromCode(10003)
	} else if size <= 0 || size > 100 {
		return nil, restful.Errors.FromCode(10003)
	}
	var kws []string
	texts, e := client.Do(kw, true)
	if e != nil {
		kws = []string{kw}
	} else {
		for _, text := range texts {
			kws = append(kws, text.Text)
		}
	}
	return &queryParam{
		Kws:     kws,
		Subject: subject,
		Page:    page,
		Size:    size,
	}, nil
}

// 查询题目
//
// 请求参数:
//
//	kw: 关键词
//	subject: 科目
//	page: 页码
//	size: 每页条数
var HANDLER_QUERY gin.HandlerFunc = func(ctx *gin.Context) {
	qp, err := NewQueryParam(ctx)
	if err != nil {
		err.Restful(ctx)
		return
	}
	//TODO
	fmt.Print(qp)
	restful.Success(ctx)
}
